package com.comp6521.project01;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

public class SortedListsGenerator {

	private String srcFile;
	private String destDir;
	private static long count = 0;
	
	public SortedListsGenerator() { }
	
	public SortedListsGenerator(String srcFile, String destDir) {
		this.setSrcFile(srcFile);
		this.setDestDir(destDir);
	}
	
	public String getSrcFile() {
		return srcFile;
	}

	public void setSrcFile(String srcFile) {
		this.srcFile = srcFile;
	}

	public String getDestDir() {
		return destDir;
	}

	public void setDestDir(String destDir) {
		this.destDir = destDir;
	}
	
	public Vector<String> generateSortedLists() {
		
		Vector<String> sortedLists = new Vector<String>();
		
		// open srcfile
		// read 2MB of data into data[]:
		// 		read line by line 
		// 		convert each string to int
		// 		store that int into data[]
		// sort data[]
		// write data[] to a sortedlist file
		// repeat until srcfile is finished
		
		// use xMBs at a time
		// x MBytes/(sizeof integer in bits / 8bits) ==> size of data[]
		final int arraySize = (3*1024*1024) / (Integer.SIZE/8);
		int [] data = new int[arraySize];
		try {
			int i = 0;
			String line;
			BufferedReader br = new BufferedReader(new FileReader(srcFile));
			while ((line = br.readLine()) != null) {
				if (i < arraySize)
					data[i] = Integer.parseInt(line);
				else
				{
					//Quicksort.quickSort(data, arraySize);
					Quicksort2 sorter = new Quicksort2();
					sorter.sort(data, arraySize);
					sortedLists.add(writeSortedList(data, arraySize));
					data = null;
					data = new int[arraySize];
					i = 0;
					data[i] = Integer.parseInt(line);
				}
				++i;
			}
			br.close();
			// sort and wrote the last sortlist
			if (data.length > 0)
			{
				//Quicksort.quickSort(data, i);
				Quicksort2 sorter = new Quicksort2();
				sorter.sort(data, i);
				sortedLists.add(writeSortedList(data, i));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sortedLists; 
	}
	
	private String writeSortedList(int[] data, int length) {
		
		String filename = destDir + "\\temp" + count + ".dat";
		++count;
		
		FileWriter writer;
		try {
			writer = new FileWriter(filename);
			for(int i = 0; i < length; ++i)
			{
				String temp = Integer.toString(data[i]);
				if (i < length - 1)
					temp += "\r\n";
				writer.write(temp);
			}
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 


		return filename;
	}

}
